<template>
  <div class="my-feedback">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">我的反馈</h1>
        <p class="page-subtitle">查看和管理我的活动反馈记录</p>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.totalFeedbacks }}</div>
              <div class="stats-label">总反馈数</div>
            </div>
            <el-icon class="stats-icon"><ChatDotRound /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.averageRating }}</div>
              <div class="stats-label">平均评分</div>
            </div>
            <el-icon class="stats-icon"><Star /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.repliedCount }}</div>
              <div class="stats-label">已回复</div>
            </div>
            <el-icon class="stats-icon"><ChatLineRound /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.pendingCount }}</div>
              <div class="stats-label">待回复</div>
            </div>
            <el-icon class="stats-icon"><Clock /></el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="活动名称">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索活动名称"
            style="width: 200px"
            clearable
            @keyup.enter="loadFeedbacks"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="评分">
          <el-select v-model="filterForm.rating" placeholder="选择评分" style="width: 120px" clearable>
            <el-option label="5分" :value="5" />
            <el-option label="4分" :value="4" />
            <el-option label="3分" :value="3" />
            <el-option label="2分" :value="2" />
            <el-option label="1分" :value="1" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="回复状态">
          <el-select v-model="filterForm.replyStatus" placeholder="选择状态" style="width: 120px" clearable>
            <el-option label="已回复" value="replied" />
            <el-option label="未回复" value="pending" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="反馈时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="loadFeedbacks">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 反馈列表 -->
    <el-card class="feedback-list-card">
      <template #header>
        <div class="card-header">
          <span>反馈记录</span>
        </div>
      </template>
      
      <div v-loading="loading" class="feedback-list">
        <div v-if="feedbacks.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无反馈记录" />
        </div>
        
        <div v-else class="feedback-items">
          <div
            v-for="feedback in feedbacks"
            :key="feedback.feedbackId"
            class="feedback-item"
          >
            <div class="feedback-header">
              <div class="activity-info">
                <h3 class="activity-title">{{ feedback.activityTitle }}</h3>
                <div class="activity-meta">
                  <span class="organizer">{{ feedback.organizerName }}</span>
                  <span class="date">{{ formatDate(feedback.createTime) }}</span>
                </div>
              </div>
              <div class="rating">
                <el-rate
                  v-model="feedback.satisfactionScore"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </div>
            </div>
            
            <div class="feedback-content">
              <div class="feedback-text">
                <h4>我的反馈：</h4>
                <p>{{ feedback.feedbackContent }}</p>
              </div>
              
              <div v-if="feedback.images && feedback.images.length > 0" class="feedback-images">
                <h4>反馈图片：</h4>
                <div class="image-list">
                  <el-image
                    v-for="(image, index) in feedback.images"
                    :key="index"
                    :src="image"
                    :preview-src-list="feedback.images"
                    :initial-index="index"
                    fit="cover"
                    class="feedback-image"
                  />
                </div>
              </div>
              
              <div v-if="feedback.replyContent" class="reply-content">
                <h4>组织者回复：</h4>
                <div class="reply-text">
                  <p>{{ feedback.replyContent }}</p>
                  <div class="reply-time">
                    回复时间：{{ formatDate(feedback.replyTime) }}
                  </div>
                </div>
              </div>
              
              <div v-else class="no-reply">
                <el-tag type="warning" size="small">待回复</el-tag>
              </div>
            </div>
            
            <div class="feedback-actions">
              <el-button type="primary" size="small" @click="viewFeedback(feedback)">
                查看详情
              </el-button>
              <el-button
                v-if="!feedback.replyContent"
                type="warning"
                size="small"
                @click="editFeedback(feedback)"
              >
                编辑反馈
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteFeedback(feedback)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="feedbacks.length > 0" class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadFeedbacks"
          @current-change="loadFeedbacks"
        />
      </div>
    </el-card>

    <!-- 反馈详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="反馈详情" width="600px">
      <div v-if="selectedFeedback" class="feedback-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="活动名称" :span="2">
            {{ selectedFeedback.activityTitle }}
          </el-descriptions-item>
          <el-descriptions-item label="组织者">
            {{ selectedFeedback.organizerName }}
          </el-descriptions-item>
          <el-descriptions-item label="满意度评分">
            <el-rate v-model="selectedFeedback.satisfactionScore" disabled />
          </el-descriptions-item>
          <el-descriptions-item label="反馈时间" :span="2">
            {{ formatDate(selectedFeedback.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="反馈内容" :span="2">
            {{ selectedFeedback.feedbackContent }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedFeedback.replyContent" label="回复内容" :span="2">
            {{ selectedFeedback.replyContent }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedFeedback.replyTime" label="回复时间" :span="2">
            {{ formatDate(selectedFeedback.replyTime) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="selectedFeedback.images && selectedFeedback.images.length > 0" class="detail-images">
          <h4>反馈图片：</h4>
          <div class="image-grid">
            <el-image
              v-for="(image, index) in selectedFeedback.images"
              :key="index"
              :src="image"
              :preview-src-list="selectedFeedback.images"
              :initial-index="index"
              fit="cover"
              class="detail-image"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑反馈对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑反馈" width="600px" @close="resetEditForm">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item label="满意度评分" prop="satisfactionScore">
          <el-rate v-model="editForm.satisfactionScore" show-text />
        </el-form-item>
        
        <el-form-item label="反馈内容" prop="feedbackContent">
          <el-input
            v-model="editForm.feedbackContent"
            type="textarea"
            :rows="4"
            placeholder="请输入您的反馈内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="反馈图片">
          <el-upload
            v-model:file-list="editForm.imageList"
            action="/api/upload"
            list-type="picture-card"
            :limit="3"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="updateFeedback" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils'
import api from '@/utils/api'
import {
  Search,
  Refresh,
  ChatDotRound,
  Star,
  ChatLineRound,
  Clock,
  Plus
} from '@element-plus/icons-vue'

const loading = ref(false)
const saving = ref(false)
const showDetailDialog = ref(false)
const showEditDialog = ref(false)
const selectedFeedback = ref(null)
const editFormRef = ref()

const feedbacks = ref([])
const stats = reactive({
  totalFeedbacks: 0,
  averageRating: 0,
  repliedCount: 0,
  pendingCount: 0
})

const filterForm = reactive({
  keyword: '',
  rating: '',
  replyStatus: '',
  dateRange: []
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const editForm = reactive({
  feedbackId: '',
  satisfactionScore: 5,
  feedbackContent: '',
  imageList: []
})

const editFormRules = {
  satisfactionScore: [
    { required: true, message: '请选择满意度评分', trigger: 'change' }
  ],
  feedbackContent: [
    { required: true, message: '请输入反馈内容', trigger: 'blur' },
    { min: 10, message: '反馈内容至少10个字符', trigger: 'blur' }
  ]
}

const loadStats = async () => {
  try {
    const response = await api.get('/student/feedback/stats')
    Object.assign(stats, response.data.data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadFeedbacks = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      size: pagination.size,
      keyword: filterForm.keyword,
      rating: filterForm.rating,
      replyStatus: filterForm.replyStatus,
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1]
    }
    
    const response = await api.get('/student/feedback', { params })
    const data = response.data.data
    
    feedbacks.value = data.list || []
    pagination.total = data.total || 0
    
  } catch (error) {
    ElMessage.error('加载反馈列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilter = () => {
  Object.assign(filterForm, {
    keyword: '',
    rating: '',
    replyStatus: '',
    dateRange: []
  })
  pagination.page = 1
  loadFeedbacks()
}

const viewFeedback = (feedback) => {
  selectedFeedback.value = feedback
  showDetailDialog.value = true
}

const editFeedback = (feedback) => {
  Object.assign(editForm, {
    feedbackId: feedback.feedbackId,
    satisfactionScore: feedback.satisfactionScore,
    feedbackContent: feedback.feedbackContent,
    imageList: feedback.images?.map(url => ({ url })) || []
  })
  showEditDialog.value = true
}

const resetEditForm = () => {
  editFormRef.value?.resetFields()
  Object.assign(editForm, {
    feedbackId: '',
    satisfactionScore: 5,
    feedbackContent: '',
    imageList: []
  })
}

const updateFeedback = async () => {
  try {
    await editFormRef.value.validate()
    
    saving.value = true
    
    const updateData = {
      satisfactionScore: editForm.satisfactionScore,
      feedbackContent: editForm.feedbackContent,
      images: editForm.imageList.map(item => item.url || item.response?.url).filter(Boolean)
    }
    
    await api.put(`/student/feedback/${editForm.feedbackId}`, updateData)
    
    ElMessage.success('反馈更新成功')
    showEditDialog.value = false
    loadFeedbacks()
    loadStats()
    
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('更新失败，请重试')
    }
  } finally {
    saving.value = false
  }
}

const deleteFeedback = async (feedback) => {
  try {
    await ElMessageBox.confirm(`确定要删除对活动"${feedback.activityTitle}"的反馈吗？`, '确认删除', {
      type: 'warning'
    })
    
    await api.delete(`/student/feedback/${feedback.feedbackId}`)
    ElMessage.success('反馈删除成功')
    loadFeedbacks()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handlePictureCardPreview = (file) => {
  console.log('预览图片:', file)
}

const handleRemove = (file, fileList) => {
  console.log('移除图片:', file, fileList)
}

onMounted(() => {
  loadStats()
  loadFeedbacks()
})
</script>

<style scoped>
.my-feedback {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.stats-row {
  margin-bottom: 24px;
}

.stats-card {
  cursor: pointer;
  transition: transform 0.3s ease;
}

.stats-card:hover {
  transform: translateY(-2px);
}

.stats-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.stats-icon {
  font-size: 32px;
  opacity: 0.3;
  color: #409eff;
}

.filter-card,
.feedback-list-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
}

.feedback-list {
  min-height: 200px;
}

.feedback-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.feedback-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  transition: box-shadow 0.3s ease;
}

.feedback-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.feedback-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.activity-info {
  flex: 1;
}

.activity-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.activity-meta {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #909399;
}

.organizer {
  font-weight: 500;
}

.feedback-content {
  margin-bottom: 16px;
}

.feedback-content h4 {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin: 0 0 8px 0;
}

.feedback-text p {
  margin: 0;
  line-height: 1.6;
  color: #303133;
}

.feedback-images {
  margin-top: 16px;
}

.image-list {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.feedback-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
}

.reply-content {
  margin-top: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.reply-text p {
  margin: 0 0 8px 0;
  color: #303133;
}

.reply-time {
  font-size: 12px;
  color: #909399;
}

.no-reply {
  margin-top: 16px;
}

.feedback-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.feedback-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-images {
  margin-top: 20px;
}

.detail-images h4 {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin: 0 0 12px 0;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
}

.detail-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  cursor: pointer;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .feedback-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .activity-meta {
    flex-direction: column;
    gap: 4px;
  }
  
  .feedback-actions {
    flex-direction: column;
  }
  
  .feedback-actions .el-button {
    width: 100%;
  }
  
  .image-list {
    justify-content: center;
  }
}
</style>